var customers = require('customers')
var CUSTOMER_DATA = require('CustomerData')
var resLoader = require('resLoader')
var UserData = require('UserData')
cc.Class({
    extends: cc.Component,

    properties: {
        customerPrefab:{
            default:null,
            type:cc.Prefab,
        },
        RestaurantList:{
            default:null,
            type:cc.Node,
        },
        PlayerGuide:{
            default:null,
            type:cc.Node,
        },
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start () {
        UserData.runtimeState.guide = this.PlayerGuide.getComponent('PlayerGuide')
        UserData.runtimeState.guide.start()
        console.log()
        if(!UserData.runtimeState.tutorialProgress.welcome){
            UserData.runtimeState.guide.start()
            UserData.runtimeState.guide.guide = UserData.runtimeState.guide.TutorialArray.welcome
            UserData.runtimeState.guide.next()
        }

        this.resList = this.RestaurantList.children
        this.customerNum = 0
        this.loadExistedCustomer()
        setInterval((self)=>{
            // self.customerNum += 1
            try{
                self.spawnCustomer(self.getRandomCustomer())
            }catch(err){
            }
        },30*100,this)
    },

    loadExistedCustomer(){
        let CustomerList =   UserData.state.globalCustomerList//UserData.acquiredCustomersList?UserData.acquiredCustomersList:[]
        if(!CustomerList){
            CustomerList = []
        }
        for(let i=0;i<CustomerList.length;i++){
            let res = this.resList[CustomerList[i].floor-1]
            this.spawnCustomer({CustomerID:CustomerList[i].custmoerID,res:res,startTime:(Date.now() -CustomerList[i].startTime)/1000},true)
        }
    },

    setCustomerFloor(ignoreCustomerLimit){ //生成可以去的楼层，把没有满员的楼层提出来。        
        let availableFloorList = []
        for(var i=0;i<this.resList.length ;i++){
            //if(this.resList[i].getComponent('Restaurant').Open!=false){
                if(ignoreCustomerLimit){
                    if(this.resList[i].getComponent('Restaurant').resSetup){
                        availableFloorList.push(this.resList[i])
                    }
                }else{
                    if(this.resList[i].getComponent('Restaurant').customerLimit>this.resList[i].getComponent('Restaurant').customerList.length && this.resList[i].getComponent('Restaurant').resSetup){
                        availableFloorList.push(this.resList[i])
                    }
                }
            //}
        }
        if(availableFloorList.length>0){
            return availableFloorList[Math.floor(Math.random()*availableFloorList.length)]
        }else{
            return null
        }
    },

    getRandomCustomer(ignoreCustomerLimit,startTime){
        let randomNum = this.getNumberInNormalDistribution(0,1)
        randomNum = Math.abs(randomNum) //0 -> +inf
        //cc.log("NormalDistribution:",randomNum)
        if(randomNum>2.5){
            randomNum = 2.5
        }
        let dayList = []
        let nightList = []
        let AQCL = UserData.acquiredCustomersList?UserData.acquiredCustomersList:[]
        
        for(let i=0;i<CUSTOMER_DATA.LIST.length;i++){
            if(AQCL.indexOf(CUSTOMER_DATA.LIST[i].id)!=-1){
                if(CUSTOMER_DATA.LIST[i].isCommonHuman){
                    dayList.push(CUSTOMER_DATA.LIST[i])
                }
                nightList.push(CUSTOMER_DATA.LIST[i])
            }
        }
        let CustomerID = null
        if(UserData.runtimeState.day){
            if(dayList.length>0){
                CustomerID = dayList[Math.floor(randomNum / 2.5 * (dayList.length-1))].id
            }
        }else{
            if(nightList.length>0){
                CustomerID = nightList[Math.floor(randomNum / 2.5 * (nightList.length-1))].id
            }
        }

        if(!startTime){
            startTime  =0
        }
        let res = null
        if(ignoreCustomerLimit){
            res = this.setCustomerFloor("ignoreCustomerLimit")
        }else{
            res = this.setCustomerFloor()
        }
        if(res){
            return {CustomerID:CustomerID,res:res,startTime:startTime}
        }else{
            return 
        }
    },
    
    spawnCustomer({CustomerID,res,startTime},loadFromRemote) {
        if(res && res.getComponent('Restaurant').floor){
            if(res.getChildByName('mask').getChildByName("背景-AnimationCancel")){
                let customer = cc.instantiate(this.customerPrefab)            
                //载入图片
                let customerSprite = customer.getChildByName('CustomerSprite').getComponent(cc.Sprite)
                resLoader.plistLoader('Customer/customers',CustomerID,customerSprite)
                //设置
                customer.zIndex = 100
                customer.getComponent('Customer').speed = Math.random()*30+20
                customer.getComponent('Customer').desinationRes =  res
                res.getComponent('Restaurant').customerList.push(customer)
                customer.getComponent('Customer').existedTime = startTime
                customer.getComponent('Customer').go()
                customer.getComponent('Customer').CustomerID = CustomerID
                for(let i=0;i<CUSTOMER_DATA.LIST.length;i++){
                    if(CustomerID == CUSTOMER_DATA.LIST[i].id){
                        customer.getComponent("Customer").customerData = CUSTOMER_DATA.LIST[i]
                        break
                    }
                }                
                //上传生成的顾客信息//更新远程数据,并获取其在远程的_id//TOBEFINISHED
                if(!loadFromRemote){
                    customers.appendCustomerInst(0,res.getComponent('Restaurant').floor,CustomerID).then((result)=>{
                })}
                //插入顾客
                res.getChildByName('mask').getChildByName('CustomerCotainer').insertChild(customer)
            }            
        }                
    },

    getNumberInNormalDistribution(mean,std_dev){
        return mean+(this.randomNormalDistribution()*std_dev);
    },
    
    randomNormalDistribution(){
        var u=0.0, v=0.0, w=0.0, c=0.0;
        do{
            //获得两个（-1,1）的独立随机变量
            u=Math.random()*2-1.0;
            v=Math.random()*2-1.0;
            w=u*u+v*v;
        }while(w==0.0||w>=1.0)
        //这里就是 Box-Muller转换
        c=Math.sqrt((-2*Math.log(w))/w);
        //返回2个标准正态分布的随机数，封装进一个数组返回
        //当然，因为这个函数运行较快，也可以扔掉一个
        //return [u*c,v*c];
        return u*c;
    },
    // update (dt) {},
});
